from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import List, Optional
import asyncio
import uvicorn
from pathlib import Path
import sys

# 添加项目根目录到PATH
sys.path.append(str(Path(__file__).parent.parent))
from agents.job_agent_system import JobAgentSystem

app = FastAPI(title="智能岗位推荐系统API",
              description="基于多智能体技术的岗位推荐系统",
              version="1.0.0")

# 设置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 初始化多智能体系统
agent_system = JobAgentSystem()

# 请求模型
class AnalysisRequest(BaseModel):
    industry: str
    years: Optional[int] = 5

class MatchRequest(BaseModel):
    user_skills: List[str]
    job_skills: List[str]

class ClusterRequest(BaseModel):
    jobs: List[dict]

# API端点
@app.post("/analyze")
async def analyze_trends(request: AnalysisRequest):
    """行业趋势分析端点"""
    try:
        analysis = await agent_system.analyze_industry_trends(request.industry)
        return {
            "success": True,
            "data": analysis,
            "message": f"{request.industry}行业分析完成"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/match")
async def match_skills(request: MatchRequest):
    """技能匹配端点"""
    try:
        score = agent_system.enhanced_skill_match(
            request.user_skills,
            request.job_skills
        )
        return {
            "success": True,
            "match_score": score,
            "message": "技能匹配完成"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/skills")
async def get_skills():
    """获取技能列表端点"""
    try:
        # 从向量数据库获取技能列表
        skills = agent_system.skill_collection.get()
        return {
            "success": True,
            "data": skills["documents"],
            "message": "技能列表获取成功"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/cluster")
async def cluster_jobs(request: ClusterRequest):
    """岗位聚类分析端点"""
    try:
        clusters = agent_system.cluster_jobs(request.jobs)
        return {
            "success": True,
            "clusters": clusters,
            "message": "岗位聚类完成"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)